import { writeFileSync, existsSync, mkdirSync, readFileSync } from "fs";
import { defineEventHandler, readBody } from "h3";

export default defineEventHandler(async (event) => {
  const body = await readBody(event);
  const { messages, action } = body;

  // Ensure data-files directory exists
  const dir = "data-files";
  if (!existsSync(dir)) {
    mkdirSync(dir);
  }

  const filePath = `${dir}/chat-history.json`;

  if (action === 'save') {
    // Save chat messages to file
    writeFileSync(filePath, JSON.stringify({ messages, timestamp: new Date().toISOString() }), "utf-8");
    return { success: true, message: 'Chat history saved' };
  } else if (action === 'load') {
    // Load chat messages from file
    if (existsSync(filePath)) {
      const data = JSON.parse(readFileSync(filePath, "utf-8"));
      return { messages: data.messages || [] };
    } else {
      return { messages: [] };
    }
  } else if (action === 'clear') {
    // Clear chat history
    if (existsSync(filePath)) {
      writeFileSync(filePath, JSON.stringify({ messages: [], timestamp: new Date().toISOString() }), "utf-8");
    }
    return { success: true, message: 'Chat history cleared' };
  }

  throw createError({
    statusCode: 400,
    statusMessage: "Invalid action",
  });
}); 